// pages/profile/profile.js
Page({
  data: {
    userInfo: {},
    version: '1.0.0',
    timeoutMinutes: 15 // 默认15分钟超时
  },

  onLoad() {
    this.getUserInfo()
    this.loadTimeoutSetting()
  },

  // 获取用户信息
  getUserInfo() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo') || {}
    this.setData({ userInfo })
  },

  // 处理选择头像事件
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      'userInfo.avatarUrl': avatarUrl
    })
    // 保存到本地存储
    const userInfo = wx.getStorageSync('userInfo') || {}
    userInfo.avatarUrl = avatarUrl
    wx.setStorageSync('userInfo', userInfo)
  },

  // 处理获取用户信息事件
  onGetUserInfo(e) {
    if (e.detail.userInfo) {
      const userInfo = e.detail.userInfo
      // 合并已有的头像URL（如果存在）
      if (this.data.userInfo.avatarUrl) {
        userInfo.avatarUrl = this.data.userInfo.avatarUrl
      }
      this.setData({ userInfo })
      wx.setStorageSync('userInfo', userInfo)
    } else {
      const customToast = this.selectComponent('#customToast')
      if (customToast) {
        customToast.showToast('请授权获取用户信息')
      }
    }
  },

  // 选择头像（已登录用户）
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        // 更新头像
        this.setData({
          'userInfo.avatarUrl': tempFilePath
        })
        // 保存到本地存储
        const userInfo = wx.getStorageSync('userInfo') || {}
        userInfo.avatarUrl = tempFilePath
        wx.setStorageSync('userInfo', userInfo)
      }
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ userInfo: {} })
          wx.removeStorageSync('userInfo')
        }
      }
    })
  },

  // 页面导航
  navigateTo(e) {
    const url = e.currentTarget.dataset.url
    
    if (url === '/pages/profile/feedback') {
      // 意见反馈 - 显示联系邮箱
      this.showContactInfo()
    } else {
      const customToast = this.selectComponent('#customToast')
      if (customToast) {
        customToast.showToast('功能开发中')
      }
    }
  },

  // 导航到小工具
  navigateToTools(e) {
    const tool = e.currentTarget.dataset.tool
    
    switch(tool) {
      case 'pomodoro':
        const pomodoroToast = this.selectComponent('#customToast')
        if (pomodoroToast) {
          pomodoroToast.showToast('番茄钟功能正在开发中，敬请期待')
        }
        break
      case 'bmi':
        const customToast = this.selectComponent('#customToast')
        if (customToast) {
          customToast.showToast('BMI计算器开发中')
        }
        break
      default:
        const toast = this.selectComponent('#customToast')
        if (toast) {
          toast.showToast('功能开发中')
        }
    }
  },

  // 加载超时设置
  loadTimeoutSetting() {
    const timeoutMinutes = wx.getStorageSync('timeoutMinutes') || 15
    this.setData({ timeoutMinutes })
  },

  // 显示超时设置
  showTimeoutSetting() {
    const timeoutOptions = ['15分钟', '20分钟', '25分钟', '30分钟', '自定义']
    const timeoutValues = [15, 20, 25, 30, 'custom']
    
    wx.showActionSheet({
      itemList: timeoutOptions,
      success: (res) => {
        if (timeoutValues[res.tapIndex] === 'custom') {
          this.showCustomTimeoutInput()
        } else {
          const selectedTimeout = timeoutValues[res.tapIndex]
          this.setData({ timeoutMinutes: selectedTimeout })
          wx.setStorageSync('timeoutMinutes', selectedTimeout)
          const customToast = this.selectComponent('#customToast')
          if (customToast) {
            customToast.showToast(`已设置为${selectedTimeout}分钟`)
          }
        }
      }
    })
  },

  // 显示自定义超时输入
  showCustomTimeoutInput() {
    wx.showModal({
      title: '自定义超时时间',
      content: '',
      editable: true,
      placeholderText: '请输入分钟数',
      success: (res) => {
        if (res.confirm && res.content) {
          const inputValue = parseInt(res.content)
          if (isNaN(inputValue) || inputValue < 1 || inputValue > 30) {
            const customToast = this.selectComponent('#customToast')
            if (customToast) {
              customToast.showToast('请输入1-30之间的数字')
            }
            return
          }
          this.setData({ timeoutMinutes: inputValue })
          wx.setStorageSync('timeoutMinutes', inputValue)
          const customToast = this.selectComponent('#customToast')
          if (customToast) {
            customToast.showToast(`已设置为${inputValue}分钟`)
          }
        }
      }
    })
  },

  // 显示联系信息
  showContactInfo() {
    wx.showModal({
      title: '联系我们',
      content: '如有任何问题或建议，请联系我们：\n\n邮箱：956513492@qq.com',
      showCancel: true,
      cancelText: '关闭',
      confirmText: '复制邮箱',
      success: (res) => {
        if (res.confirm) {
          // 复制邮箱到剪贴板
          wx.setClipboardData({
            data: '956513492@qq.com',
            success: () => {
              const customToast = this.selectComponent('#customToast')
              if (customToast) {
                customToast.showToast('邮箱已复制')
              }
            }
          })
        }
      }
    })
  },

  // 分享小程序
  shareApp() {
    wx.showShareMenu({
      withShareTicket: true,
      success: () => {
        // 直接触发分享
        wx.updateShareMenu({
          withShareTicket: true,
          success: () => {
            const customToast = this.selectComponent('#customToast')
            if (customToast) {
              customToast.showToast('点击右上角更多按钮分享给好友')
            }
          }
        })
      },
      fail: () => {
        // 如果上面的方法不支持，就显示提示
        const customToast = this.selectComponent('#customToast')
        if (customToast) {
          customToast.showToast('点击右上角更多按钮分享给好友')
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '一个超好用的便便记录小程序，关注健康从记录开始！',
      path: '/pages/start/start',
      imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
    }
  },

  /**
   * 用户点击分享到朋友圈
   */
  onShareTimeline: function () {
    return {
      title: '一个超好用的便便记录小程序，关注健康从记录开始！',
      query: 'from=timeline',
      imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
    }
  }
})